import requests

from uuid import uuid4

headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
        'Cookie' : 'BDqhfp=Python%26%26-10-1undefined%26%260%26%261; BIDUPSID=6768C8D1FEB792A335068924BFDFA6F1; PSTM=1569494897; BAIDUID=4852010FF8250F54FF4C7ABA18ADD025:FG=1; BDUSS=81SFFDbVlSZkoyeC1QVm9xUExIc0NuYlR4UGEtaHZjSU16bEtWSFZvdUF-OFJkRVFBQUFBJCQAAAAAAAAAAAEAAADnO5NHUmFpbmdFeWUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBynV2Acp1dNW; stoken=ff407b59b206475a1de919d6197c447a8339944f62b2bc4e69e70c272be59292; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; userFrom=www.baidu.com; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; indexPageSugList=%5B%22Python%22%2C%22%E7%99%BE%E5%BA%A6%E5%9B%BE%E7%89%87%22%2C%22%E7%BD%97%E5%B0%8F%E9%BB%91%22%2C%22%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91%20%22%5D; cleanHistoryStatus=0',
        'Referer' : 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1572673933962_R&pv=&ic=&nc=1&z=&hd=&latest=&copyright=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=Python'
}

session = requests.session()
session.headers = headers

def get_img(url):
    html = session.get(url)
    if html.status_code == 200:
        html.encoding = 'utf-8'
        content = html.json()['data']
        for c in content[:-1]:
            download(c['middleURL'])
            print(c['middleURL'])
    else:
        print("ERROR: ", url)


def download(imgurl):

    image = session.get(imgurl)
    print('正在下载{}'.format(imgurl))
    with open('./img/{}.jpg'.format(uuid4()), 'wb') as f:
        for chunk in image.iter_content(225):
            f.write(chunk)
if __name__ == '__main__':
    url = 'https://image.baidu.com/search/acjson?tn=r' \
          'esultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=' \
          'Python&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=' \
          '&latest=&copyright=&word=Python&s=&se=&tab=&width=&height=&fa' \
          'ce=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn=60&rn=30&gsm=&1572673947712='


    get_img(url)



